import * as fabricjs from 'fabric';
const { fabric } = fabricjs;
import { v4 as uuidv4 } from 'uuid';

/**
 * 文本插件 - 提供添加和编辑文本的功能
 */
export default class TextPlugin {
    static pluginName = 'TextPlugin';
    static apis = ['addText', 'addHeading', 'addSubheading', 'updateTextStyle', 'updateTextContent'];

    constructor(canvas, editor) {
        this.canvas = canvas;
        this.editor = editor;
        this.defaultFontFamily = 'Arial';
        this.defaultFill = '#333333';
    }

    // 添加普通文本
    addText(text = '输入文字', options = {}) {
        const textObj = new fabric.IText(text, {
            left: 100,
            top: 100,
            fontFamily: this.defaultFontFamily,
            fontSize: 20,
            fill: this.defaultFill,
            id: uuidv4(),
            name: '文本',
            ...options
        });

        this.canvas.add(textObj);
        this.canvas.setActiveObject(textObj);
        this.canvas.renderAll();

        this.editor.emit('text:added', textObj);
        return textObj;
    }

    // 添加标题
    addHeading(text = '标题文本', options = {}) {
        return this.addText(text, {
            fontSize: 36,
            fontWeight: 'bold',
            name: '标题',
            ...options
        });
    }

    // 添加副标题
    addSubheading(text = '副标题文本', options = {}) {
        return this.addText(text, {
            fontSize: 24,
            name: '副标题',
            ...options
        });
    }

    // 更新文本样式
    updateTextStyle(property, value) {
        const activeObject = this.canvas.getActiveObject();
        if (!activeObject || !this._isTextObject(activeObject)) return;

        // 处理特殊样式切换 (bold, italic, underline)
        if (property === 'fontWeight' && activeObject.fontWeight === 'bold') {
            activeObject.set('fontWeight', 'normal');
        } else if (property === 'fontStyle' && activeObject.fontStyle === 'italic') {
            activeObject.set('fontStyle', 'normal');
        } else if (property === 'underline' && activeObject.underline) {
            activeObject.set('underline', false);
        } else {
            activeObject.set(property, value);
        }

        this.canvas.renderAll();
        this.editor.emit('text:styled', { object: activeObject, property, value });
    }

    // 设置文本内容
    updateTextContent(text) {
        const activeObject = this.canvas.getActiveObject();
        if (!activeObject || !this._isTextObject(activeObject)) return;

        activeObject.set('text', text);
        this.canvas.renderAll();
    }

    // 检查对象是否为文本对象
    _isTextObject(obj) {
        return obj.type === 'i-text' || obj.type === 'text' || obj.type === 'textbox';
    }
}